package com.xunk.scene.controller;

import cn.hutool.core.util.ObjectUtil;
import com.xunk.common.core.exception.CustomException;
import com.xunk.common.core.utils.StringUtils;
import com.xunk.common.core.utils.serialization.JsonSerializer;
import com.xunk.common.core.web.domain.AjaxResult;
import com.xunk.common.redis.service.RedisService;
import com.xunk.common.security.utils.SecurityUtils;
import com.xunk.scene.constant.SceneConstant;
import com.xunk.scene.domain.AddOrUpdateScene;
import com.xunk.scene.mapper.SceneMapper;
import com.xunk.scene.service.SceneService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ProjectName: HIM
 * @Package: com.xunk.scene.controller
 * @ClassName: ClickController
 * @Author: tangguangyuan
 * @Description:点击执行场景
 * @Date: 2021/5/12 14:10
 * @Version: 1.0
 */
@RestController
@RequestMapping(value = "/click")
@Slf4j
public class ClickController {

    @Autowired
    private SceneService sceneService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SceneMapper sceneMapper;

    /**
     * 点击执行场景
     *
     * @param sceneId
     * @return
     */
    @GetMapping(value = "/exec")
    public AjaxResult execCron(@RequestParam(value = "sceneId") Long sceneId,
                               @RequestParam(value = "homeId") Long homeId) {
        AjaxResult ajaxResult = AjaxResult.error();
        //防止执行时再次执行，对场景添加redis锁
        try {
            boolean result = redisService.tryLock("scene:lock:" + sceneId, String.valueOf(sceneId), 3, false);
            //锁设置失败
            if (!result) {
                ajaxResult = AjaxResult.error("场景执行中!");
            } else {
                //如果是场景模板，查询场景，保存场景
                final Long realSceneId = sceneService.getRealSceneId(sceneId, homeId, StringUtils.EMPTY);
                if (ObjectUtil.isNotEmpty(realSceneId)) {
                    sceneId = realSceneId;
                }
                Long userId = SecurityUtils.getUserId();
                List<Long> homeIds = sceneService.getHomeIds(userId);
                if (!homeIds.contains(homeId)) {
                    log.info("当前userid：{}与homeid：{}不存在绑定关系，修改场景失败", userId, homeId);
                    throw new CustomException("用户与家庭不存在绑定关系，不允许执行场景");
                }
                int count = sceneMapper.selectCountByHomeIdAndSceneId(homeId, sceneId);
                if (count < 1) {
                    log.info("当前homeId：{}与sceneId：{}不存在绑定关系，修改场景失败", homeId, sceneId);
                    return AjaxResult.error("不存在绑定关系，不允许执行场景");
                }
                //锁设置成功，执行场景动作
                ajaxResult = sceneService.execSceneAction(String.valueOf(sceneId), StringUtils.EMPTY);
            }
        } catch (CustomException e) {
            ajaxResult = AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            log.info("场景执行出现异常：{}", e);
            ajaxResult = AjaxResult.error("场景执行出现异常");
        } finally {
            //释放锁
            redisService.unlock("scene:lock:" + sceneId, String.valueOf(sceneId));
            return ajaxResult;
        }
    }
}
